#!/usr/bin/env python
#coding:utf-8
from hashlib import sha1
import os, time
 
 
 
create_session_id = lambda: sha1('%s%s' % (os.urandom(16), time.time())).hexdigest()

session_container = {}


class SessionFactory(object):
    
    @staticmethod
    def Session(httphandler,timeout=1800):
        session = Session(httphandler,timeout)
        return session
    


class Session(object):
    '''自定义session框架'''
     
    _sessionid = '__sessionid__'
     
    def __init__(self,request,timeout):
        #根据request从cookie中获取 __sessionid 的值
        self._request = request
        self._timeout  = 1800
        self._redis = {}
        self.__initialize()
         
    def __initialize(self):
        id = self._request.get_cookie(Session._sessionid)
        if not id:
            id = create_session_id()
        self._request.set_cookie(Session._sessionid,id)
        self._id = id
    
    def __getitem__(self,name):
        #return self._redis.hget(self._id, name)
        try:
            data = session_container[self._id][name]
        except Exception,e:
            data = None
        return data
     
    def __setitem__(self,name,value):
        #self._redis.hset(self._id, name, value)
        #self._redis.expire(self._id, self.session_lifetime)
        if session_container.has_key(self._id):
            session_container[self._id][name] = value
        else:
            temp = {name:value}
            session_container[self._id] = temp
        
    def __delitem__(self, name):
        #return self._redis.hdel(self._id, name)
        del session_container[self._id][name]
         
__all__ = ["SessionFactory"]